package com.mxt.moviedemo.controller;

import com.mxt.moviedemo.entity.*;
import com.mxt.moviedemo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class SuccessPageController {
    @Autowired
    private UserService userService;
    @Autowired
    private MoviesService moviesService;
    @Autowired
    private ActorsService actorsService;
    @Autowired
    private DirectorsService directorsService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private ReviewsService reviewsService;

    @GetMapping("/ticketPage")
    public String showTicketPage(@RequestParam("mid") int mid,
                                 @RequestParam("username") String username,
                                 @RequestParam("mtitle") String mtitle,
                                 Model model) {
        // 根据 mid 获取电影信息
        Movies movie = moviesService.getMovieById(mid);
        if (movie != null) {
            model.addAttribute("movie", movie);
        } else {
            // 处理电影信息获取失败的情况
            // 可以添加错误信息到 model 中，然后在页面显示错误提示
            model.addAttribute("error", "未能获取到电影信息");
        }
        model.addAttribute("username", username);
        model.addAttribute("mtitle", mtitle);
        return "ticketPage";
    }

    @PostMapping("/buyTicket")
    public String buyTicket(@RequestParam("mid") int mid,
                            @RequestParam("username") String uname,
                            @RequestParam("count") int count,
                            @RequestParam("totalPrice") String totalPrice,
                            Model model) {
        User user = userService.getUserByUsername(uname);
        Movies movie = moviesService.getMovieById(mid);

        if (user != null && movie != null) {
            double userBalance = Double.parseDouble(user.getBalance());
            double ticketTotalPrice = Double.parseDouble(totalPrice);

            if (userBalance >= ticketTotalPrice) {
                // 余额充足，扣除相应价格
                double newBalance = userBalance - ticketTotalPrice;
                user.setBalance(String.valueOf(newBalance));
                userService.updateUser(user);

                // 保存订单信息
                Ticket ticket = new Ticket();
                ticket.setUuid(user.getUuid());
                ticket.setUname(uname);
                ticket.setMname(movie.getMtitle());
                ticket.setPrice(movie.getPrice());
                ticket.setCount(count);
                ticket.setTotalprice(totalPrice);

                // 将 Date 对象转换为符合 datetime 格式的字符串
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String otime = sdf.format(new Date());
                ticket.setOtime(otime);

                ticketService.saveTicket(ticket);

                // 添加成功信息
                model.addAttribute("success", "购票成功！");
                model.addAttribute("movie", movie);
                model.addAttribute("username", uname);
                model.addAttribute("mtitle", movie.getMtitle());
                return "ticketPage";
            } else {
                // 余额不足，返回错误信息
                model.addAttribute("error", "余额不足，请充值后再尝试购票。");
                model.addAttribute("movie", movie);
                model.addAttribute("username", uname);
                model.addAttribute("mtitle", movie.getMtitle());
                return "ticketPage";
            }
        } else {
            // 处理用户或电影信息获取失败的情况
            model.addAttribute("error", "未能获取到用户或电影信息，请稍后重试。");
            model.addAttribute("username", uname);
            return "ticketPage";
        }
    }
    @GetMapping("/movieInfo")
    public String showMovieInfo(@RequestParam("mid") int mid,
                                @RequestParam(name = "username", required = false) String username,
                                Model model) {
        // 根据电影 ID 获取电影信息
        Movies movie = moviesService.getMovieById(mid);
        if (movie == null) {
            // 处理电影信息获取失败的情况
            model.addAttribute("error", "未能获取到电影信息");
            return "successPage"; // 跳转
        }
        movie.setGeners(moviesService.getMovieGeners(mid));
        movie.setActors(moviesService.getMovieActors(mid));
        movie.setDirectors(moviesService.getMovieDirectors(mid));

        List<Reviews> reviews = reviewsService.getReviewsByMovieId(mid);

        model.addAttribute("movie", movie);
        model.addAttribute("username", username);
        model.addAttribute("reviews", reviews);
        return "movieInfo";
    }
    @GetMapping("/successPage")
    public String showSuccessPage(@RequestParam(name = "username", required = false) String username,
                                  @RequestParam(name = "page", defaultValue = "0") int page,
                                  @RequestParam(name = "size", defaultValue = "10") int size,
                                  Model model) {
        if (username != null && !username.isEmpty()) {
            model.addAttribute("username", username);
        }
        // 创建分页请求参数对象
        PageRequest pageRequest = new PageRequest(page, size);
        // 获取分页电影列表
        var pageResult = moviesService.getMoviesByPage(pageRequest);
        List<Movies> movies = pageResult.getData();
        // 过滤掉null元素
        List<Movies> nonNullMovies = new ArrayList<>();
        for (Movies movie : movies) {
            if (movie != null) {
                nonNullMovies.add(movie);
            }
        }
        model.addAttribute("movies", nonNullMovies);

        // 计算总页数
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);

        return "successPage";
    }

    @GetMapping("/adminSuccessPage")
    public String showAdminSuccessPage(@RequestParam(name = "username", required = false) String username,
                                       @RequestParam(name = "page", defaultValue = "0") int page,
                                       @RequestParam(name = "size", defaultValue = "10") int size,
                                       Model model) {
        model.addAttribute("username", username);
        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<User> pageResult = userService.getUsersByPage(pageRequest);
        List<User> Users = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);


        model.addAttribute("Users", Users);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);

        return "adminPage";
    }

    @GetMapping("/adminSearchUsersPage")
    public String searchUsers(@RequestParam(name = "username", required = false) String username,
                              @RequestParam(name = "searchUsername", required = false) String searchUsername,
                              @RequestParam(name = "page", defaultValue = "0") int page,
                              @RequestParam(name = "size", defaultValue = "10") int size,
                              Model model) {
        model.addAttribute("username", username);
        model.addAttribute("searchUsername", searchUsername);

        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<User> pageResult = userService.getUsersByPage(pageRequest);
        List<User> Users = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);

        List<User> allUsers = userService.searchUsersByName(searchUsername);
        model.addAttribute("allUsers", allUsers);


        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);


        return "adminPage";
    }
    @GetMapping("/adminTicketsPage")
    public String showAdminTicketsPage(@RequestParam(name = "username", required = false) String username,
                                       @RequestParam(name = "page", defaultValue = "0") int page,
                                       @RequestParam(name = "size", defaultValue = "10") int size,
                                       Model model) {
        model.addAttribute("username", username);
        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<Ticket> pageResult = ticketService.getTicketsByPage(pageRequest);
        List<Ticket> tickets = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);

        model.addAttribute("tickets", tickets);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);

        return "adminTicketsPage";
    }


    @GetMapping("/adminMoviesPage")
    public String showAdminMoviesPage(@RequestParam(name = "username", required = false) String username,
                                      @RequestParam(name = "page", defaultValue = "0") int page,
                                      @RequestParam(name = "size", defaultValue = "10") int size,
                                      Model model) {
        model.addAttribute("username", username);
        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<Movies> pageResult = moviesService.getMoviesByPage(pageRequest);
        List<Movies> movies = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);

        model.addAttribute("movies", movies);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);

        return "adminMoviesPage";
    }
    @GetMapping("/adminGenersPage")
    public String showAdminGenersPage(@RequestParam(name = "username", required = false) String username,
                                      @RequestParam(name = "page", defaultValue = "0") int page,
                                      @RequestParam(name = "size", defaultValue = "10") int size,
                                      Model model) {
        model.addAttribute("username", username);
        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<Geners> pageResult = moviesService.getGenersByPage(pageRequest);
        List<Geners> geners = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);

        model.addAttribute("geners", geners);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages-1);
        model.addAttribute("pageSize", size);

        return "adminGenersPage";
    }
    @GetMapping("/adminDirectorsPage")
    public String showAdminDirectorsPage(@RequestParam(name = "username", required = false) String username,
                                         @RequestParam(name = "page", defaultValue = "0") int page,
                                         @RequestParam(name = "size", defaultValue = "10") int size,
                                         Model model) {
        model.addAttribute("username", username);
        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<Directors> pageResult = directorsService.getDirectorsByPage(pageRequest);
        List<Directors> directors = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);

        model.addAttribute("directors", directors);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);

        return "adminDirectorsPage";
    }
    @GetMapping("/adminActorsPage")
    public String showAdminActorsPage(@RequestParam(name = "username", required = false) String username,
                                      @RequestParam(name = "page", defaultValue = "0") int page,
                                      @RequestParam(name = "size", defaultValue = "10") int size,
                                      Model model) {
        model.addAttribute("username", username);
        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<Actors> pageResult = actorsService.getActorsByPage(pageRequest);
        List<Actors> actors = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);

        model.addAttribute("actors", actors);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);

        return "adminActorsPage";
    }
    @GetMapping("/adminReviewsPage")
    public String showAdminReviewsPage(@RequestParam(name = "username", required = false) String username,
                                       @RequestParam(name = "page", defaultValue = "0") int page,
                                       @RequestParam(name = "size", defaultValue = "10") int size,
                                       Model model) {
        model.addAttribute("username", username);
        PageRequest pageRequest = new PageRequest(page, size);
        PageResult<Reviews> pageResult = reviewsService.getReviewsByPage(pageRequest);
        List<Reviews> reviews = pageResult.getData();
        long totalPages = (long) Math.ceil((double) pageResult.getTotal() / size);

        model.addAttribute("reviews", reviews);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", size);

        return "adminReviewsPage";
    }

    @GetMapping("/search")
    public String search(@RequestParam("keyword") String keyword,
                         @RequestParam(value = "username", required = false) String username,
                         @RequestParam(value = "page", defaultValue = "0") int page,
                         @RequestParam(value = "size", defaultValue = "10") int size,
                         Model model) {
        PageRequest pageRequest = new PageRequest(page,size);

        PageResult<Movies> moviesResult = moviesService.searchMoviesByKeyword(pageRequest, keyword);
        PageResult<Actors> actorsResult = actorsService.searchActorsByKeyword(pageRequest, keyword);
        PageResult<Directors> directorsResult = directorsService.searchDirectorsByKeyword(pageRequest, keyword);

        model.addAttribute("keyword", keyword);


        model.addAttribute("movies", moviesResult.getData());
        model.addAttribute("actors", actorsResult.getData());
        model.addAttribute("directors", directorsResult.getData());


        model.addAttribute("username", username);
        model.addAttribute("pageSize", size);

        return "userSearchPage";
    }
    @GetMapping("/userPage")
    public String showUserPage(@RequestParam(name = "username", required = false) String username,
                               Model model) {
        if (username == null || username.isEmpty()) {
            return "redirect:/successPage";
        }
        User user = userService.getUserByUsername(username);
        if (user != null) {
            model.addAttribute("user", user);
        }
        return "userPage";
    }
}